package com.defense;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class StuList {
    JFrame jf = new JFrame("学生列表");
    final int width = 800;
    final int height = 600;

    private JTable table;

    public void init() {
        jf.setBounds((Toolkit.getDefaultToolkit().getScreenSize().width - width) / 2,
                (Toolkit.getDefaultToolkit().getScreenSize().height - height) / 2,
                width, height);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLayout(new BorderLayout());

        // 创建顶部面板
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0));

        // 创建左侧面板，放置输入框，并设置最大宽度以确保与右侧面板对齐
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.X_AXIS));
        leftPanel.setMaximumSize(new Dimension(width / 2, 50));

        // 创建输入框和标签
        JLabel studentIdLabel = new JLabel("学号：");
        JTextField studentIdField = new JTextField(10);
        JLabel groupLeaderLabel = new JLabel("组长：");
        JTextField groupLeaderField = new JTextField(10);

        // 将标签和输入框添加到左侧面板
        leftPanel.add(studentIdLabel);
        leftPanel.add(studentIdField);
        leftPanel.add(Box.createHorizontalStrut(10));
        leftPanel.add(groupLeaderLabel);
        leftPanel.add(groupLeaderField);

        // 创建右侧面板，放置按钮
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0));
        rightPanel.setMaximumSize(new Dimension(width / 2, 50));

        // 创建按钮
        JButton queryButton = new JButton("查询");
        JButton backButton = new JButton("返回");
        JButton deleteButton = new JButton("删除");

        // 为返回按钮添加事件监听器
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MangerInterface mangerInterface = new MangerInterface();
                mangerInterface.init();
                jf.setVisible(false);
                jf.dispose();
            }
        });

        // 为查询按钮添加事件监听器
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取输入框中的学号和组长信息
                String studentId = studentIdField.getText();
                String groupLeader = groupLeaderField.getText();

                // 从文件中查找匹配的数据
                List<String[]> dataList = searchDataInFiles(studentId, groupLeader);

                // 对数据列表进行排序，先按照组长列排序，再按照学号升序排序
                Collections.sort(dataList, new Comparator<String[]>() {
                    @Override
                    public int compare(String[] o1, String[] o2) {
                        int groupLeaderCompare = o1[1].compareTo(o2[1]);
                        if (groupLeaderCompare == 0) {
                            return o1[0].compareTo(o2[0]);
                        }
                        return groupLeaderCompare;
                    }
                });

                // 创建表格模型
                Object[][] data = new Object[dataList.size()][2];
                for (int i = 0, j = dataList.size(); i < j; i++) {
                    data[i][0] = dataList.get(i)[0]; // 学号列
                    data[i][1] = dataList.get(i)[1]; // 组长名列
                }
                String[] columnNames = {"学号", "组长"};

                // 创建表格
                table = new JTable(data, columnNames);

                // 表格添加到滚动面板
                JScrollPane scrollPane = new JScrollPane(table);

                jf.add(scrollPane, BorderLayout.CENTER);

                jf.validate();
                jf.repaint();
            }
        });

        // 为删除按钮添加事件监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow != -1) {
                    // 获取要删除的学号和组长信息
                    String studentIdToDelete = (String) table.getValueAt(selectedRow, 0);
                    String groupLeaderToDelete = (String) table.getValueAt(selectedRow, 1);

                    // 从表格模型中删除数据
                    DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
                    tableModel.removeRow(selectedRow);

                    // 从id.txt和names.txt文件中删除对应的数据
                    deleteDataFromFiles(studentIdToDelete, groupLeaderToDelete);

                    JOptionPane.showMessageDialog(jf, "删除成功！");
                } else {
                    JOptionPane.showMessageDialog(jf, "请先选中要删除的行！");
                }
            }
        });

        // 将按钮添加到右侧面板
        rightPanel.add(queryButton);
        rightPanel.add(backButton);
        rightPanel.add(deleteButton);

        // 将左右面板添加到顶部面板
        topPanel.add(leftPanel);
        topPanel.add(rightPanel);

        // 将顶部面板添加到主窗口
        jf.add(topPanel, BorderLayout.NORTH);

        // 显示窗口
        jf.setVisible(true);
    }

    // 在id.txt和name.txt文件中查找匹配数据的方法
    private List<String[]> searchDataInFiles(String studentId, String groupLeader) {
        List<String[]> dataList = new ArrayList<>();
        try {
            BufferedReader idReader = new BufferedReader(new FileReader("id.txt"));
            BufferedReader nameReader = new BufferedReader(new FileReader("names.txt"));

            String idLine;
            String nameLine;

            while ((idLine = idReader.readLine()) != null && (nameLine = nameReader.readLine()) != null) {
                if (idLine.contains(studentId) && nameLine.contains(groupLeader)) {
                    dataList.add(new String[]{idLine, nameLine});
                }
            }

            idReader.close();
            nameReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return dataList;
    }

    // 从id.txt和names.txt文件中删除对应数据的方法
    private void deleteDataFromFiles(String studentId, String groupLeader) {
        List<String> updatedIdList = new ArrayList<>();
        List<String> updatedNameList = new ArrayList<>();

        try {
            BufferedReader idReader = new BufferedReader(new FileReader("id.txt"));
            BufferedReader nameReader = new BufferedReader(new FileReader("names.txt"));

            String idLine;
            String nameLine;

            while ((idLine = idReader.readLine()) != null && (nameLine = nameReader.readLine()) != null) {
                if (!idLine.equals(studentId) && !nameLine.equals(groupLeader)) {
                    updatedIdList.add(idLine);
                    updatedNameList.add(nameLine);
                }
            }

            idReader.close();
            nameReader.close();

            // 将更新后的列表重新写入文件
            FileWriter idWriter = new FileWriter("id.txt");
            FileWriter nameWriter = new FileWriter("names.txt");

            for (String id : updatedIdList) {
                idWriter.write(id + "\n");
            }
            idWriter.close();

            for (String name : updatedNameList) {
                nameWriter.write(name + "\n");
            }
            nameWriter.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new StuList().init();
    }
}
